<template>
  <el-card v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.96)" shadow="always">
    <!-- 设置固定表头，但是要计算一下窗口的高度，动态分配height值 -->
    <el-table
      v-if="tableData.length > 0"
      :data="tableDataSort"
      @selection-change="selectWhich"
      style="width: 100%"
      :row-key="getRowKey"
      border
      v-infinite-scroll="loadData"
      infinite-scroll-disabled="noMore"
      infinite-scroll-immediate="false"
      :row-class-name="topItem"
    >
      <el-table-column type="selection" reserve-selection width="55"></el-table-column>
      <el-table-column
        v-for="item in secondValue"
        :key="item.name"
        :prop="item.type"
        :label="item.name"
        :min-width="item.width"
        :[item.fi]="item.guo || filterFun(tableData, item.filter)"
        :[item.mo]="(value, row) => item.fang(value, row) || filterTag(value, row, item.filter)"
      ></el-table-column>
      <el-table-column label="附件" :formatter="formatter"></el-table-column>
      <el-table-column fixed="right" label="操作" width="186">
        <template slot-scope="scope">
          <el-button v-if="!isAdmin" @click.native.prevent="setTop(scope.row)" type="text" size="small">置顶</el-button>
          <el-button
            v-if="!isAdmin && scope.row.level > 100"
            @click.native.prevent="deleteTop(scope.row)"
            type="text"
            size="small"
            >取消置顶</el-button
          >
          <el-button type="text" size="small" @click.native.prevent="showRow(scope.row)">查看</el-button>
          <el-button v-if="!isAdmin" type="text" style="color: #f56c6c" size="small" @click.native.prevent="deleteRow(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-alert v-else title="暂无数据，点击上方[新增]按钮新增数据" type="info" center :closable="false"></el-alert>
    <div class="loadingdiv">{{ more }}</div>
  </el-card>
</template>

<script>
let BaaS = window.BaaS;
import { findData, deleteData, $isLogin, updateData } from "@/assets/crud";
import $ from "jquery";
export default {
  isAdmin: false,
  name: "myTable",
  props: ["firstValue", "secondValue", "token"],
  data() {
    return {
      tableData: [],
      initialData: [],
      loading: true,
      noMore: false,
      more: "",
    };
  },
  computed: {
    tableDataSort() {
      let sortData = this.tableData;
      sortData.sort((x, y) => y.level - x.level);
      return sortData;
    },
  },
  methods: {
    topItem({ row }) {
      if (row.level > 100) {
        return "top-row";
      } else {
        return "";
      }
    },
    formatter(row) {
      if (row.files != undefined && row.files.path.length) {
        return "有";
      } else {
        return "无";
      }
    },
    setTop(row) {
      let level = new Date().getTime();
      updateData("answer", row._id, "level", level)
        .then(() => {
          row.level = level;
          this.$message.success("置顶成功！");
        })
        .catch(() => {
          this.$message.error("置顶失败！请检查网络");
        });
    },
    deleteTop(row) {
      updateData("answer", row._id, "level", 100)
        .then(() => {
          row.level = 100;
        })
        .catch(() => {
          this.$message.error("取消置顶失败！请检查网络");
        });
    },
    loadData() {
      this.noMore = true;
      setTimeout(() => {
        let length = this.tableData.length;
        if (length) {
          this.more = "加载中...";
          this.getSomeAnswer(length)
            .then((res) => {
              if (res.data.objects.length) {
                this.tableData = this.tableData.concat(res.data.objects.map(this.transformData));
                this.initialData = this.initialData.concat(res.data.objects);
                this.noMore = false;
                this.more = "";
              } else {
                this.more = "没有更多了";
              }
            })
            .catch(() => {
              this.$message.error("拉取失败!请检查网络");
              this.noMore = false;
              this.more = "";
            });
        }
      }, 700);
    },
    async getAnswer() {
      await this.getSomeAnswer()
        .then((res) => {
          this.initialData = res.data.objects;
          this.tableData = this.initialData.map(this.transformData);
        })
        .catch(() => {
          this.$message.error("加载失败!请检查网络");
        });
      this.loading = false;
    },
    getSomeAnswer(offset) {
      let userId = BaaS.storage.get("uid");
      let query = new BaaS.Query();
      query.compare("docType", "=", this.firstValue);
      if (BaaS.storage.get("ok")) {
        let query1 = new BaaS.Query();
        query1.contains("ok", String(userId));
        let andQuery = BaaS.Query.and(query1, query);
        return findData("answer", andQuery, ["id", "answer", "docType", "status", "created_by", "created_at", "level"], offset);
      } else {
        query.compare("created_by", "=", userId);
        return findData("answer", query, ["id", "answer", "docType", "status", "created_by", "created_at", "level"], offset);
      }
    },
    // 选中项
    selectWhich(selection) {
      this.$emit("selectItem", selection);
    },
    // 必须指定唯一key
    getRowKey(row) {
      return row._id;
    },
    transformData(x) {
      let obj = JSON.parse(x.answer);
      return Object.assign(obj, { _id: x.id, status: x.status, level: x.level });
    },
    deleteRow(row) {
      this.$confirm("确认删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "点错了",
        type: "error",
      })
        .then(() => {
          this.loading = true;
          deleteData("answer", row._id)
            .then(() => {
              setTimeout(() => {
                this.deleteThis(row);
                this.loading = false;
              }, 300);
              $.ajax(`http://120.78.68.201:3000/rmdir/id_${BaaS.storage.get("uid")}/${row.files.time}`, {
                headers: {
                  Authorization: this.token,
                },
              });
            })
            .catch(() => {
              this.$message.error("删除失败!");
            });
        })
        .catch((err) => err);
    },
    deleteThis(row) {
      let A = this.tableData.findIndex((s) => s._id == row._id);
      this.$delete(this.tableData, A);
      let B = this.initialData.findIndex((s) => s.id == row._id);
      this.$delete(this.initialData, B);
    },
    showRow(row) {
      BaaS.storage.set(
        "currentItem",
        this.initialData.find((s) => s.id == row._id)
      );
      switch (this.firstValue) {
        case "论文":
          this.$router.push("/home/paper");
          break;
        case "专利":
          this.$router.push("/home/patent");
          break;
        case "项目":
          this.$router.push("/home/project");
          break;
        case "获奖":
          this.$router.push("/home/awarded");
          break;
        default:
          break;
      }
    },
    filterFun(tableData, index) {
      let arr = tableData.map((s) => s[index]);
      let b = new Set(arr);
      arr = [...b].sort();
      if (arr[0] != undefined) {
        return arr.map((x) => {
          return { text: x, value: x };
        });
      }
    },
    filterTag(value, row, key) {
      return row[key] == value;
    },
  },
  created() {
    this.getAnswer();
    this.isAdmin = BaaS.storage.get("ok");
  },
  beforeRouteEnter(to, from, next) {
    $isLogin(next);
  },
  watch: {
    firstValue() {
      this.loading = true;
      this.getAnswer();
    },
  },
};
</script>

<style>
.loadingdiv {
  text-align: center;
  margin: 5px 0 0 0;
  font-size: 10px;
  height: 0.1px;
}
.el-table .top-row {
  background: #ecf5ff;
}
</style>
